//
//  ZSBWorkOrdorSearchListView.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2017/12/14.
//  Copyright © 2017年 zjhcsoftios. All rights reserved.
//

#import "ZSBWorkOrdorSearchListView.h"
#import "ZSBWordOrdorSearchConditionView.h"
#import "ZsbWorkOrdorSearchCell.h"
#import "SVProgressHUD.h"
#import "UIColor+Ex.h"
#import "NSBundle+AssociatedBundle.h"

#define iSEESCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
@interface ZSBWorkOrdorSearchListView() <UITableViewDelegate,UITableViewDataSource,ZsbWorkOrdorSearchCellDelegate>

@property (nonatomic, strong) OrdorSearchListSuccessBlock success;
@property (nonatomic, strong) OrdorSearchListFailedBlock fail;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TopViewHeiht;
@property (weak, nonatomic) IBOutlet UIButton *updateButton;
@property (weak, nonatomic) IBOutlet UIButton *cannelButton;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, strong) NSMutableArray *dataList;

@property (nonatomic, strong) ZSBWorkSearchListModel *model;

@property (nonatomic, strong) ZSBSearchModel *sortModel;

@property (nonatomic, strong) ZSBSearchModel *upDownModel;

@property (weak, nonatomic) IBOutlet UIButton *sortByButton;
@property (weak, nonatomic) IBOutlet UIButton *updownButton;

@end


@implementation ZSBWorkOrdorSearchListView


static NSString *workOrdorSearchListViewIdentify = @"workOrdorSearchListViewIdentify";

- (void)awakeFromNib {
    [super awakeFromNib];
    _dataList = [NSMutableArray array];
    _table.delegate = self;
    _table.dataSource = self;
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table.backgroundColor = [UIColor clearColor];
    [_table registerNib:[UINib nibWithNibName:@"ZsbWorkOrdorSearchCell" bundle:[NSBundle bundleWithURL:[[NSBundle bundleForClass:[self class]] URLForResource:@"NewMarketLib" withExtension:@"bundle"]]] forCellReuseIdentifier:workOrdorSearchListViewIdentify];
//    [_table setEditing:YES animated:YES];
    _sortModel = [[ZSBSearchModel alloc] init];
    _upDownModel = [[ZSBSearchModel alloc] init];
    
    
    _updownButton.layer.borderColor = [UIColor colorWithHexString:@"DBDDE1"].CGColor;
    _updownButton.layer.cornerRadius = 3;
    _updownButton.layer.borderWidth = 1;
    
    _sortByButton.layer.borderColor = [UIColor colorWithHexString:@"DBDDE1"].CGColor;
    _sortByButton.layer.cornerRadius = 3;
    _sortByButton.layer.borderWidth = 1;
    
    
    [_sortByButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -_sortByButton.imageView.image.size.width, 0, _sortByButton.imageView.image.size.width)];
    [_sortByButton setImageEdgeInsets:UIEdgeInsetsMake(0, _sortByButton.titleLabel.bounds.size.width, 0, -_sortByButton.titleLabel.bounds.size.width)];
}


- (void)setModel:(ZSBWorkSearchListModel *)model {
    _model = model;
    _upDownModel = _model.order.data[0];
    
    if (_model.orderName.data.count > 0) {
        _sortModel = _model.orderName.data[0];
        [_sortByButton setTitle:_sortModel.name forState:UIControlStateNormal];
    }
    for (ZSBSearchModel *tempModel in _model.serchName.data) {
        tempModel.searchText = @"";
    }
    
}


- (IBAction)addButtonAction:(UIButton *)sender {

    [self endEditing:YES];
    
    [ZSBWordOrdorSearchConditionView showSearchPickerInView:self array:_model.serchName.data success:^(ZSBSearchModel *successModel) {
        if (![self modelIsInDataList:successModel]) {
            
            [self.dataList addObject:successModel];
            [self.table reloadData];
        }
    } failure:^{
        
    }];
}

- (BOOL)modelIsInDataList:(ZSBSearchModel *) successModel {
    for (ZSBSearchModel *tempModel in _dataList) {
        if ([tempModel.name isEqualToString:successModel.name]) {
            [SVProgressHUD showErrorWithStatus:@"搜索字段已存在"];
            return YES;
        }
    }
    return NO;
}


- (IBAction)updateButtonAction:(UIButton *)sender {
    
    NSMutableArray *searchArray = [NSMutableArray array];
    for (ZSBSearchModel *cellModel in _dataList) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:cellModel.value, @"name", cellModel.searchText,@"key", nil];
        [searchArray addObject:dic];
    }
    
    NSDictionary *ordorDic = [NSDictionary dictionaryWithObjectsAndKeys:_sortModel.value, @"name", _upDownModel.value, @"way", _sortModel.orderType, @"valueType", nil];
    
    if (searchArray.count > 0) {
        
        NSDictionary *successDic = [NSDictionary dictionaryWithObjectsAndKeys:searchArray, @"searchCol", [NSArray arrayWithObject:ordorDic], @"orderCol", nil];
        _success(successDic);
        [self removeFromSuperview];
    }else {
        NSDictionary *successDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:ordorDic], @"orderCol", nil];
        _success(successDic);
        [self removeFromSuperview];
    }
    
    
}


- (IBAction)cannelButtonAction:(UIButton *)sender {
    
    if (self.fail) {
        self.fail();
    }
    [self removeFromSuperview];
}

+ (void)showSearchPickerInView:(UIView *) view
                         model:(ZSBWorkSearchListModel*) model
                       success:(OrdorSearchListSuccessBlock) success
                       failure:(OrdorSearchListFailedBlock) fail {
    ZSBWorkOrdorSearchListView *conditionView = [[NSBundle bundleWithURL:[[NSBundle bundleForClass:[self class]] URLForResource:@"NewMarketLib" withExtension:@"bundle"]] loadNibNamed:@"ZSBWorkOrdorSearchListView" owner:self options:nil].lastObject;
    conditionView.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, [UIScreen mainScreen].bounds.size.height);
    conditionView.model = model;
    conditionView.success = success;
    conditionView.fail = fail;
    [conditionView.table reloadData];
    [view addSubview:conditionView];
}




#pragma mark table 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZsbWorkOrdorSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:workOrdorSearchListViewIdentify forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.delegate = self;

    cell.model = _dataList[indexPath.row];

    return cell;
}









#ifdef __IPHONE_8_0

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
            ZSBSearchModel *tempModel = self.dataList[indexPath.row];
            tempModel.searchText = @"";
            [self.dataList removeObjectAtIndex:indexPath.row];
            
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            
            
        }];
        
        rowAction.backgroundColor = [UIColor colorWithRed:0.9862 green:0.0071 blue:0.0274 alpha:1.0];
        NSArray *arr = @[rowAction];
        return arr;

    
    
}

#else

/**
 *  修改Delete按钮文字为“删除”
 */
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    return @"删除";

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        // 删除模型

            ZSBSearchModel *tempModel = _dataList[indexPath.row - 1];
            tempModel.searchText = @"";
            [self.dataList removeObjectAtIndex:indexPath.row - 1];
            
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#endif




#pragma cellDelegate

- (void)searchCellSearchBarFinished:(ZSBSearchModel *)model AtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row != 0) {
        
        _dataList[indexPath.row - 1] = model;
        [_table reloadData];
    }
}

- (void)titleButtonActionWithIndexPath:(NSIndexPath *) indexPath {
    if (indexPath.row == 0) {

        [ZSBWordOrdorSearchConditionView showSearchPickerInView:self array:_model.orderName.data success:^(ZSBSearchModel *successModel) {
            
            self.sortModel = successModel;
            self.upDownModel = self.model.order.data[0];
            [self.table reloadData];

        } failure:^{
            
        }];
        
    }
}


- (IBAction)upDownButtonAction:(UIButton *) sender {
    
    ZSBSearchModel *tempModel = _model.order.data[0];
    
    if ([_upDownModel.name isEqualToString:tempModel.name]) {
        _upDownModel = _model.order.data[1];
    }else {
        _upDownModel = _model.order.data[0];
    }
    
    [sender setImage:[self getImageFromBundle:_upDownModel.name] forState:UIControlStateNormal];
    
    [self.table reloadData];
}

- (IBAction)sortByButtonAction:(UIButton *)sender {
    
    [ZSBWordOrdorSearchConditionView showSearchPickerInView:self array:_model.orderName.data success:^(ZSBSearchModel *successModel) {
        
        self.sortModel = successModel;
        self.upDownModel = self.model.order.data[0];

        [sender setTitle:self.sortModel.name forState:UIControlStateNormal];
        
        [sender setTitleEdgeInsets:UIEdgeInsetsMake(0, -sender.imageView.image.size.width, 0, sender.imageView.image.size.width)];
        [sender setImageEdgeInsets:UIEdgeInsetsMake(0, sender.titleLabel.bounds.size.width, 0, -sender.titleLabel.bounds.size.width)];
        
        [self.updownButton setImage:[self getImageFromBundle:self.upDownModel.name] forState:UIControlStateNormal];
        
    } failure:^{
        
    }];
}

- (void)setUpDownModel:(ZSBSearchModel *)upDownModel {
    
}



- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self endEditing:YES];
    
    
}

- (UIImage *)getImageFromBundle:(NSString *)imageName {
    return [UIImage imageNamed:imageName inBundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"] compatibleWithTraitCollection:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
